//给你一个链表，删除链表的倒数第 n 个结点，并且返回链表的头结点。 
//
// 进阶：你能尝试使用一趟扫描实现吗？ 
//
// 
//
// 示例 1： 
//
// 
//输入：head = [1,2,3,4,5], n = 2
//输出：[1,2,3,5]
// 
//
// 示例 2： 
//
// 
//输入：head = [1], n = 1
//输出：[]
// 
//
// 示例 3： 
//
// 
//输入：head = [1,2], n = 1
//输出：[1]
// 
//
// 
//
// 提示： 
//
// 
// 链表中结点的数目为 sz 
// 1 <= sz <= 30 
// 0 <= Node.val <= 100 
// 1 <= n <= sz 
// 
// Related Topics 链表 双指针 👍 1624 👎 0

package leetcode.editor.cn;



import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class _19_RemoveNthNodeFromEndOfList {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5};
        for (int i = 0, j = nums.length - 1; i < j; i++, j--) {
            int tmp = nums[i];
            nums[i] = nums[j];
            nums[j] = tmp;
        }
        ListNode head = new ListNode(nums[0], null);
        ListNode tmp = null;
        for (int i = 1; i < nums.length; i++) {
            tmp = new ListNode(nums[i], head);
            head = tmp;
        }
        Solution solution = new _19_RemoveNthNodeFromEndOfList().new Solution();
        ListNode listNode = solution.removeNthFromEnd(head, 2);
        show(listNode);
    }

    public static void show(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head == null) {
                return head;
            }
            ListNode fast = head;
            ListNode low = head;
            while (n > 0) {
                fast = fast.next;
                n--;
            }
            if (fast == null) {
                head = head.next;
            } else {
                while (fast.next != null) {
                    fast = fast.next;
                    low = low.next;
                }
                low.next = low.next.next;
            }
            return head;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}